package com.maybach.core.flow.security;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.maybach.core.security.AdminUser;
import com.maybach.core.security.AdminUserUtil;
import com.maybach.util.AssertUtil;
import com.maybach.workflow.common.api.WorkFlowContext;
import com.maybach.workflow.common.api.enums.ActorTypeEnum;
import com.maybach.workflow.common.api.exception.FlowException;
import com.maybach.workflow.common.model.FlowTaskActorDO;
import com.maybach.workflow.core.service.SecurityService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.List;

/**
 * Created by houenxun on 16/1/21.
 * shiro 版本的实现
 */
public class DefaultSecurityService implements SecurityService {

    @Override
    public boolean isPermitted(WorkFlowContext context, FlowTaskActorDO taskActorDO) {
        Subject subject = SecurityUtils.getSubject();
        if (ActorTypeEnum.user.name().equals(taskActorDO.getActorType())) {
            return (null != subject.getPrincipal() && String.valueOf(subject.getPrincipal()).equals(taskActorDO.getValue()));
        } else if (ActorTypeEnum.role.name().equals(taskActorDO.getActorType())) {
            return subject.hasRole(taskActorDO.getValue());
        } else if (ActorTypeEnum.permission.name().equals(taskActorDO.getActorType())) {
            subject.isPermitted(taskActorDO.getValue());
        } else if(ActorTypeEnum.anonymous.name().equals(taskActorDO.getActorType())){
            return true;
        }else{
            throw new FlowException("未知的权限类型", null).setContext(context);
        }
        return false;
    }

    @Override
    public String getUserName() {
        AdminUser adminUser = AdminUserUtil.getUser();
        if(StringUtils.isNotEmpty(adminUser.getRealName())){
            return adminUser.getRealName();
        }else if(StringUtils.isNotEmpty(adminUser.getNickName())) {
            return adminUser.getNickName();
        }else {
            return adminUser.getLoginName();
        }
    }

    @Override
    public Long getUserId() {
        AdminUser adminUser = AdminUserUtil.getUser();
        return adminUser.getAdminId();
    }

    @Override
    public String getUserLable() {
        AdminUser adminUser = AdminUserUtil.getUser();
        return adminUser.getDepartmentName();
    }

    @Override
    public boolean isPermitted(WorkFlowContext context, List<FlowTaskActorDO> taskActorList) {
        AssertUtil.notNull(taskActorList,"taskActorList" );
        for(FlowTaskActorDO taskActorDO : taskActorList){
            if(this.isPermitted(context, taskActorDO)){
                if(null != context) {
                    context.setTaskActor(taskActorDO);
                }
                return true;
            }
        }

        return false;
    }

}
